<?php

namespace App\Http\Controllers\Api\Index;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Modules\Index\Services\GlucoseService;
use App\Modules\Index\Services\InsulinService;
use App\Modules\Index\Services\diningTimeService;
use App\Modules\Index\Services\WarningService;
use App\Modules\Index\Services\PrescriptionService;
use App\Modules\Index\Models\Prescription;
use App\Modules\System\Models\SetMedicinal;
use App\Modules\Task\Services\TaskService;
use App\Modules\Jpush\Services\JpushService;
use Config;
use DB;

class GlucoseController extends Controller
{

    /**
     * 添加血糖
     */
    function addGlucose(Request $request){
        //数据验证
        $uid = $this->getLoginUser()->id;
        $glu =$request->input('glu','');
        $device_code = $request->input('device_code','');
        $meals = $request->input('meals',1);
        $diet = $request->input('diet','');
        $sport = $request->input('sport','');
        $remark = $request->input('remark');
        $test_at = $request->input('test_at');
        $state = $request->input('state');
        $type = $request->input('type');


        if ( empty($uid) || empty($glu)) return response()->error("PARAM_EMPTY");

        $merge['user_id'] = $uid;
        $merge['meals'] = $meals;
        $merge['time'] = $test_at;
        $merge['glucose'] = $glu;
        $merge['sign'] = 1;

        if ($state == 1) $merge['type'] = '正常';
        else if ($state == 2) $merge['type'] = '偏低';
        else if ($state == 3) $merge['type'] = '偏高';

        $merge['created_at'] = date('Y-m-d H:i:s');
        $merge['updated_at'] = date('Y-m-d H:i:s');
        $result = InsulinService::addMergeInsulin($merge);


        //添加血糖
        $dataAddArr = [
            'user_id'         => $uid,
            'glu'         => $glu,
            'device_code'          => $device_code,
            'meals'   => $meals,
            'diet'        => $diet,
            'sport'         => $sport,
            'remark'          => $remark,
            'test_at'       =>$test_at,
            'state'       =>$state,
            'type'       =>$type
        ];

        $result = GlucoseService::addGlu($dataAddArr);
        if ( !$result ) return response()->error("ADD_FAILURE");
        if($meals == 7) {
            $taskObj = new TaskService();
            $taskObj->taskMeasurement($uid);
        }
        return response()->success();

    }

    /**
     * 胰岛素列表
     */
    function insulinList(){
        $result = InsulinService::insulinList();
        foreach($result as $key => $value){
            $result[$key]['image'] = env('APP_DOMAIN').$value['image'];
            if($value['insulin_type'] == 'SHORT_ACTING' || $value['insulin_type'] == 'RAPID_ACTING'){
                $data['shot'][] = $result[$key];
            }else if($value['insulin_type'] == 'INTERMEDIATE_ACTING'){
                $data['intermediate'][] = $result[$key];
            }else if($value['insulin_type'] == 'BASAL'){
                $data['basal'][] = $result[$key];
            }else if($value['insulin_type'] == 'PREMIXED'){
                $data['premixed'][] = $result[$key];
            }

        }
        return response()->success($data);

    }

    /**
     * 添加胰岛素
     */
    function addInsulin(Request $request){
        //数据验证
        $user_id = $this->getLoginUser()->id;
        $type = $request->input('type');
        $id = $request->input('id');
        if ( empty($user_id) || empty($type) ||empty($id) ) return response()->error("PARAM_EMPTY");
        $dataAddArr = array();
        if($type == 2){
            $data = SetMedicinal::from('set_medicinal AS S')->select(['S.id','S.user_id','S.medicinal_id','S.meals','S.insulin_dosage','S.status','M.medicinal_cn','M.medicinal_en','M.insulin_type','M.insulin_preparation'])->leftJoin('medicinal AS M','M.id','=','S.medicinal_id')
                ->where('S.user_id',$user_id)->where('S.status',1)->where('S.id',$id)->where('M.status',1)->first()->toArray();
            if($data){
                $dataAddArr = [
                    'user_id'         => $user_id,
                    'insulin_name_cn'         => $data['medicinal_cn'],
                    'insulin_name_en'         => $data['medicinal_en'],
                    'insulin_type'         =>  $data['insulin_type'],
                    'insulin_preparation'         => $data['insulin_preparation'],
                    'insulin_dosage'          =>$data['insulin_dosage'],
                    'type'          => $type,
                    'meals'          => $data['meals'],
                    'maked_at'   => date('Y-m-d H:i:s')
                ];
            }
        }else if($type == 1){
            $data = Prescription::where('id',$id)->first()->toArray();

            if($data){

                $dataAddArr = [
                    'user_id'         => $user_id,
                    'prescription_id' => $id,
                    'insulin_name_cn'         => $data['insulin_name_cn'],
                    'insulin_name_en'         => $data['insulin_name_en'],
                    'insulin_type'         =>  $data['insulin_type'],
                    'insulin_preparation'         => $data['insulin_preparation'],
                    'insulin_dosage'          =>$data['final_units'],
                    'type'          => $type,
                    'meals'          => $data['meals'],
                    'maked_at'   => date('Y-m-d H:i:s')
                ];
            }
        }
        if($dataAddArr){

            $res = InsulinService::addInsulin($dataAddArr);

            switch($dataAddArr['meals']){
                case 1;
                    $merge ['meals'] = 1;
                    break;
                case 2;
                    $merge ['meals'] = 3;
                    break;
                case 3;
                    $merge ['meals'] = 5;
                    break;
                case 4;
                    $merge ['meals'] = 7;
                    break;
            }

            $merge['user_id'] = $user_id;
//            $merge['meals'] = $dataAddArr['meals'];
            $merge['time'] = $dataAddArr['maked_at'];
            $merge['glucose'] = $dataAddArr['insulin_name_cn'];
            $merge['type'] = $dataAddArr['insulin_dosage'];
            $merge['sign'] = 2;
            $merge['created_at'] = date('Y-m-d H:i:s');
            $merge['updated_at'] = date('Y-m-d H:i:s');
            $result = InsulinService::addMergeInsulin($merge);

            if ( !$res ) return response()->error("ADD_FAILURE");
        }



        return response()->success();
    }

    /**
     * 日志查询接口
     */
    function userGlucoseLog(Request $request){
        $data['time'] = $request->input('time');
        $data['user_id'] =  $this->getLoginUser()->id;
        if ( empty($data['user_id']) ) return response()->error("PARAM_EMPTY");
        $result = GlucoseService::userGlucoseLog($data);
        return response()->success($result);
    }

    /**
     * 日志查询接口
     */
    function userGlucoseLogIos(Request $request){
        $data['time'] = $request->input('time');
        $data['user_id'] =  $this->getLoginUser()->id;
        if ( empty($data['user_id']) ) return response()->error("PARAM_EMPTY");
        $result = GlucoseService::userGlucoseLogIos($data);
        return response()->success($result);
    }

    /**
     * 日统计
     */
    function dayLog(Request $request){
        $param['time'] = $request->input('time',date('Y-m-d'));
        $param['user_id'] = $this->getLoginUser()->id;
        if(empty($param['user_id'])) return response()->error("PARAM_EMPTY");
        $result =  GlucoseService::dayLog($param);
        return response()->success($result);

    }

    /**
     * 按周统计或月统计
     */

    function monthLog(Request $request){
        $param['user_id'] = $this->getLoginUser()->id;
        $param['state'] = $request->input('state',2);//1按周 2按月
//        p($param);
        if(empty($param['user_id'])) return response()->error("PARAM_EMPTY");
        $result =  GlucoseService::userLog($param);
        return response()->success($result);
    }



    /**
     * 用户餐前餐后的基本信息
     */
    function userDinner(){
        $user_id = $this->getLoginUser()->id;
        $result = InsulinService::userDinner($user_id);
        return response()->success($result);

    }

    /**
     * 合并数据 xxx
     */
    function mergeInsulin(){
        $result = InsulinService::mergeInsulin();
        if($result) echo '成功';
    }

    /**
     * 用户设置用餐时间范围
     */
    function mealsTime(){
        $user_id = $this->getLoginUser()->id;
        $result = diningTimeService::mealsTime($user_id);
        return response()->success($result);
    }

    /**
     * 用户首页血糖显示
     */
    function indexData(){
        $user_id = $this->getLoginUser()->id;
        $result = GlucoseService::index($user_id);
        return response()->success($result);

    }

    /**
     * 设备数据
     * @return mixed
     */
    function deviceData(){
        $user_id = $this->getLoginUser()->id;
        $result = GlucoseService::deviceData($user_id);
        return response()->success($result);
    }

    /**
     * 添加设备数据
     */
    function deviceUpdate(Request $request){
        $user_id = $this->getLoginUser()->id;
        $id = $request->input('id');
        $diet = $request->input('diet','');
        $sport = $request->input('sport','');
        $remark = $request->input('remark','');
        if(empty($id))  return response()->error("PARAM_EMPTY");
        if(empty($diet) && empty($sport) && empty($remark)){
            return response()->error("PARAM_EMPTY");
        }
        $data = array(
            'diet'   =>   $diet,
            'sport'  =>   $sport,
            'remark' =>   $remark
        );
        $result = GlucoseService::deviceUpdate($id,$user_id,$data);
        if ( !$result ) return response()->error("UPDATE_FAILURE");
        return response()->success();
    }

    /**
     * 查看异常报警
     */

    function readWarning(){
        $user_id = $this->getLoginUser()->id;
        $result = WarningService::readWarning($user_id);
        return response()->success($result);
    }

    /**
     * 查询用户处方建议
     */
    function userPrescription(){
        $user_id = $this->getLoginUser()->id;
        $result = PrescriptionService::userPrescription($user_id);
        return response()->success($result);

    }

    /**
     *用户用药记录列表
     */
    function userMedicinal(){
        $user_id = $this->getLoginUser()->id;
        $result = PrescriptionService::userMedicinal($user_id);
        return response()->success($result);
    }

    /**
     *获取用户的处方建议报告
     */
    function getPrescription(){
        $result = PrescriptionService::vipUserRecommend(1);

    }

    /**
     *用户餐别和当前时间的血糖范围
     */
    function userMealsNormal(Request $request){
        $user_id =$this->getLoginUser()->id;
        $time = $request->input('time');
        $result = diningTimeService::userMealsNormal($user_id,$time);
        return response()->success($result);
    }

    /*
     * 消息推送
     */
//    function push(){
//        $param['platform'] = 'android';
//        $param['title'] = '糖伯伯jpush';
//        $param['content'] = '糖伯伯';
//        $param['user_id'] = array(
//            '40',
//            '41'
//        );
//        $param['builderId'] = '0';
//        $param['type'] = '2';
//        $param['alias'] = '';
//        $param['extras'] = '';
//        $res = JpushService::jgPush($param);
//        return $res;
//    }
}

?>